package middleware

import (
	"bytes"
	"cashcenter/internal/discovery"
	"cashcenter/internal/service"
	"cashcenter/utils/errx"
	"cashcenter/utils/resx"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"io/ioutil"
)

func CaptchaMiddleware() gin.HandlerFunc {
	return func(context *gin.Context) {
		// 获取请求信息
		dataBytes, err := context.GetRawData()
		if err != nil {
			context.JSON(200, resx.GinResp(resx.SystemErr, err))
			context.Abort()
			return
		}
		data := CommonCaptchaRequest{}
		json.Unmarshal(dataBytes, &data)

		// 校验数据
		if data.Captcha == "" || data.Email == "" || data.Operate == "" {
			context.JSON(200, resx.GinResp(resx.BadRequest, nil))
			context.Abort()
			return
		}

		// 发送邮箱验证码验证
		//emailServiceClient := context.Keys["email"].(service.EmailServiceClient)
		//rpcResp, err := emailServiceClient.EmailVerifyCaptcha(context, &service.EmailCaptchaVerifyRequest{
		//	Operate: data.Operate,
		//	Email:   data.Email,
		//	Captcha: data.Captcha,
		//})
		emailConn := discovery.EmailDiscover.Get()
		if emailConn == nil {
			context.JSON(200, resx.GinResp(resx.SystemErr, errx.CtpError(errx.RpcError)))
			context.Abort()
			return
		}
		emailServiceClient := service.NewEmailServiceClient(emailConn)
		rpcResp, err := emailServiceClient.EmailVerifyCaptcha(context, &service.EmailCaptchaVerifyRequest{
			Operate: data.Operate,
			Email:   data.Email,
			Captcha: data.Captcha,
		})
		if rpcResp.GetCode() == 14 {
			discovery.EmailDiscover.Sad(emailConn.Target())
		}

		if err != nil {
			context.JSON(200, resx.GinResp(resx.SystemErr, err))
			context.Abort()
			return
		}
		if rpcResp.Code != 1200 {
			context.JSON(200, resx.GinResp(resx.Fail, rpcResp.Code))
			context.Abort()
			return
		}

		// 数据归位
		context.Request.Body = ioutil.NopCloser(bytes.NewBuffer(dataBytes))
		context.Next()
	}
}

type CommonCaptchaRequest struct {
	Email   string `json:"email" binding:"required"`
	Captcha string `json:"captcha" binding:"required"`
	Operate string `json:"operate" binding:"required"`
}
